package com.example.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.baidu.mapapi.model.LatLng;
import com.example.juyixia.R;
import com.example.mathutil.JuyixiaUtil;
import com.exanple.data.Activeinfo;
import com.example.juyixia.Map_shopInfo;
import android.app.Dialog;
import android.app.Service;
import android.R.integer;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.content.DialogInterface.OnClickListener;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * 监听活动回复的服务
 * 
 * @author Administrator
 * 
 */
public class ActiveService extends Service {
	private boolean isRun;
	public static final String bm = "utf-8";
	private Handler handler1; // 显示当前时间线程消息处理器。
	private Handler handler2;
	private JSONObject recjson;
	private int num;// 参与人数
	private int currentnum;// 当前人数
	private double alllongitude;
	private double alllatitude;
	private double avealllongitude;
	private double avealllatitude;
	private String activeCreaterLoca;
	private String ips[];
	// 聚会相关
	private String k1;// 从主服务器获得的四个秘钥
	private String k2;
	private String k3;
	private String k4;
	private String r1;
	private String r2;
	private String r3;
	private String meetlocation;// 得到聚会地点
	private String data;// 商铺的字符串信息

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	public boolean isHostConnectable(String host, int port) {
		Socket socket = new Socket();
		try {
			socket.connect(new InetSocketAddress(host, port));
			PrintWriter out = new PrintWriter(new BufferedWriter(
					new OutputStreamWriter(socket.getOutputStream(), bm)), true);
			out.println(recjson.toString());
			out.close();

			// 关闭Socket
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return true;

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub

		num = Integer.parseInt(intent.getStringExtra("人数"));
		switch (Integer.parseInt(intent.getStringExtra("id"))) {
		case 1:
			activeCreaterLoca = "29.494749,106.576843";
			break;
		case 2:
			activeCreaterLoca = "29.495300,106.581111";
			break;
		case 3:
			activeCreaterLoca = "29.493586,106.581191";
			break;
		case 4:
			activeCreaterLoca = "29.496447,106.578065";
			break;
		}
		currentnum = 0;
		isRun = true;
		alllatitude = 0;// 重置纬度
		alllongitude = 0;// 重置经度
		new Thread(new Runnable() {

			@Override
			public void run() {
				// 定义一个线程中止标志

				try {

					ServerSocket serverSocket = new ServerSocket(22222);
					while (isRun) {
						Socket client = serverSocket.accept();
						currentnum++;
						BufferedReader in = new BufferedReader(
								new InputStreamReader(client.getInputStream(),
										bm));
						String str = in.readLine();
						recjson = new JSONObject(str);
						if (currentnum <= num) {
							alllatitude += Double.parseDouble(recjson
									.getString("坐标").split(",")[0]);
							alllongitude += Double.parseDouble(recjson
									.getString("坐标").split(",")[1]);
						}
						if (currentnum == num) {
							alllongitude += Double
									.parseDouble(activeCreaterLoca.split(",")[1]);
							alllatitude += Double.parseDouble(activeCreaterLoca
									.split(",")[0]);
							avealllongitude = alllongitude / (num + 1);
							avealllatitude = alllatitude / (num + 1);
							Map_shopInfo.meetlocation = new LatLng(avealllatitude, avealllongitude);
							Message msg = new Message();
							handler2.sendMessage(msg);
							Activeinfo.activelist.add(new Activeinfo(recjson
									.getString("活动名"),
									recjson.getString("参与者"), "2017.6.9"));
							ips = recjson.getString("allip").split(",");
							try {
								Socket socket = new Socket("172.16.96.250",
										54235);
								// 向服务器发送一个空数据
								PrintWriter pw = new PrintWriter(
										new BufferedWriter(
												new OutputStreamWriter(socket
														.getOutputStream(), bm)),
										true);
								pw.println(" ");
								// 接收服务器的数据
								BufferedReader br = new BufferedReader(
										new InputStreamReader(socket
												.getInputStream(), bm));
								String message = br.readLine();
								// 对接收到的数据进行解析
								String[] k = message.split(",");
								k1 = k[0];
								k2 = k[1];
								k3 = k[2];
								k4 = k[3];
								String[] shopareas = { k[4], k[5], k[6], k[7],
										k[8], k[9] };
								meetlocation = getMeetLocation(shopareas);
								// 关闭流
								pw.close();
								br.close();
								socket.close();

								// ----------------------------------------
								// 请求子服务器1
								Socket socket1 = new Socket("172.16.96.250",
										54323);
								// 向服务器发送个空数据
								PrintWriter pw1 = new PrintWriter(
										new BufferedWriter(
												new OutputStreamWriter(socket1
														.getOutputStream(), bm)),
										true);
								pw.println(" ");
								// 接收服务器的数据
								BufferedReader br1 = new BufferedReader(
										new InputStreamReader(socket
												.getInputStream(), bm));
								r1 = br1.readLine();
								// 关闭流
								pw1.close();
								br1.close();
								socket1.close();
								// ----------------------------------------
								// 请求子服务器2
								Socket socket2 = new Socket("172.16.96.250",
										54324);
								// 向服务器发送一个空数据
								PrintWriter pw2 = new PrintWriter(
										new BufferedWriter(
												new OutputStreamWriter(socket1
														.getOutputStream(), bm)),
										true);
								pw.println(" ");
								// 接收服务器的数据
								BufferedReader br2 = new BufferedReader(
										new InputStreamReader(socket
												.getInputStream(), bm));
								r2 = br1.readLine();
								// 关闭流
								pw2.close();
								br2.close();
								socket2.close();
								// ----------------------------------------
								// 请求子服务器3
								Socket socket3 = new Socket("172.16.96.250",
										54325);
								// 向服务器发送一个空数据
								PrintWriter pw3 = new PrintWriter(
										new BufferedWriter(
												new OutputStreamWriter(socket1
														.getOutputStream(), bm)),
										true);
								pw.println(" ");
								// 接收服务器的数据
								BufferedReader br3 = new BufferedReader(
										new InputStreamReader(socket
												.getInputStream(), bm));
								r3 = br1.readLine();
								// 关闭流
								pw3.close();
								br3.close();
								socket3.close();
								// 请求子服务器4
								Socket socket4 = new Socket("172.16.96.250",
										54326);
								// 向服务器发送数据
								PrintWriter pw4 = new PrintWriter(
										new BufferedWriter(
												new OutputStreamWriter(socket1
														.getOutputStream(), bm)),
										true);
								String key = JuyixiaUtil.MAC(meetlocation, k4);
								pw.println(key);
								// 接收服务器的数据
								BufferedReader br4 = new BufferedReader(
										new InputStreamReader(socket
												.getInputStream(), bm));
								String ss = br4.readLine();
								BASE64Decoder dec = new BASE64Decoder();
								byte[] after = null;
								after = dec.decodeBuffer(ss);// 使用BASE64解码
								String mess = new String(after);
								// 得到商铺信息的字符串
								String shopmess = JuyixiaUtil.xor(mess, r1, r2, r3);
								//将计算得到的商铺信息再BASE64加密准备传输
								BASE64Encoder enc=new BASE64Encoder();
								data = enc.encodeBuffer(shopmess.getBytes());
								String[] a = shopmess.split("]");
								String[] b = a[0].split(";");
								String[] c = a[1].split(";");
								String[] d = a[2].split(";");
								Map_shopInfo.infos.add(new Map_shopInfo(b[2], b[0], b[1],R.drawable.shop1));
								Map_shopInfo.infos.add(new Map_shopInfo(c[2], c[0], c[1],R.drawable.shop2));
								Map_shopInfo.infos.add(new Map_shopInfo(d[2], d[0], d[1],R.drawable.shop3));
								// 关闭流
								pw4.close();
								br4.close();
								socket4.close();
							} catch (UnknownHostException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							new Thread() {
								public void run() {
									try {

										for (String ip : ips) {
											// if(isHostConnectable(ip, 54321)){
											// continue;
											// }
											Socket socket = null;
											try {
												// 创建Socket
												// socket = new
												// Socket("192.168.1.110",54321);
												socket = new Socket(ip, 47777);

												// 向服务器发送消息
												PrintWriter out = new PrintWriter(
														new BufferedWriter(
																new OutputStreamWriter(
																		socket.getOutputStream(),
																		bm)),
														true);
												String lo = ""+avealllatitude+","+avealllongitude+"";
												out.println(recjson.toString()+"?"+data+"?"+lo);
												out.close();

												// 关闭Socket
												socket.close();
											} catch (Exception e) {
												// TODO: handle exception

											}
										}

									} catch (Exception e) {
										// TODO: handle exception

									}

								}

							}.start();
						}
						Message msg = new Message();
						handler1.sendMessage(msg);

					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
		handler1 = new Handler(new Handler.Callback() {// 这样写，就不弹出什么泄漏的警告了
					@Override
					public boolean handleMessage(Message msg) {
						try {
							Toast.makeText(
									getApplicationContext(),
									recjson.getString("用户名") + "同意参与，"
											+ ips.length + "坐标为："
											+ recjson.getString("坐标"),
									Toast.LENGTH_SHORT).show();
						} catch (NotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						return false;
					}
				});
		handler2 = new Handler(new Handler.Callback() {// 这样写，就不弹出什么泄漏的警告了
					@Override
					public boolean handleMessage(Message msg) {
						try {
							Toast.makeText(
									getApplicationContext(),
									"平均坐标为：" + avealllatitude + ","
											+ avealllongitude,
									Toast.LENGTH_SHORT).show();
						} catch (NotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						return false;
					}
				});
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		isRun = false;
	}

	private String getMeetLocation(String[] str) {
		double nearlylong = avealllongitude;
		double nearlyla = avealllatitude;
		double[] location = new double[6];
		for (String s : str) {
			for (double d : location) {
				d = Double.parseDouble(s);
			}
		}
		if(Math.abs(location[0]-avealllongitude)>=Math.abs(location[2]-avealllatitude))
			nearlylong = location[2];
		else
			nearlylong = location[0];
		if(Math.abs(location[4]-avealllongitude)>=Math.abs(location[2]-avealllongitude))
			nearlylong = location[2];
		else
			nearlylong = location[4];
		if(Math.abs(location[1]-avealllatitude)>=Math.abs(location[3]-avealllatitude))
			nearlylong = location[3];
		else
			nearlylong = location[0];
		if(Math.abs(location[5]-avealllatitude)>=Math.abs(location[3]-avealllatitude))
			nearlylong = location[3];
		else
			nearlylong = location[5];
		String result = String.valueOf(nearlylong)+","+String.valueOf(nearlyla);
		return result;
	}
}
